﻿using AutoMapper;
using MediatR;
using Warehouse.Api.Write.AllCation.Command.Shifing;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Write.AllCation.Hanlder
{
    public class AddShiftingCommandHanlder : IRequestHandler<AddShiftingCommand, ApiResult<int>>
    {
        public readonly IMapper mapper;
        public readonly IBaseRepostity<Shifting> baseRepostity;
        public readonly ILogger<AddShiftingCommandHanlder> logger;

        public AddShiftingCommandHanlder(IMapper mapper, IBaseRepostity<Shifting> baseRepostity, ILogger<AddShiftingCommandHanlder> logger)
        {
            this.mapper = mapper;
            this.baseRepostity = baseRepostity;
            this.logger = logger;
        }
        /// <summary>
        /// 添加移库和调拨信息表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public Task<ApiResult<int>> Handle(AddShiftingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var model = mapper.Map<Shifting>(request);
                int r = baseRepostity.InsertAsync(model).Result;
                if (r > 0)
                {
                    result.Msg = "添加成功";
                    logger.LogInformation("添加移库和调拨信息表成功");
                    result.Data = r;
                    result.Code = ApiEume.Success;
                }
                else
                {
                    result.Msg = "添加失败";
                    logger.LogInformation("添加移库和调拨信息表失败");
                    result.Data = r;
                    result.Code = ApiEume.Error;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加移库和调拨信息表异常");
            }
            return Task.FromResult(result);
        }
    }

}
